using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Lidgren.Network;

namespace MvdDonk.Bomberman.Network.Messages
{
    public class PositionMessage : IMessage
    {
        public char Action { get { return 'P'; } }
        public long NetworkId { get; set; }
        public Vector2 Position { get; private set; }

        public PositionMessage(Vector2 position)
        {
            Position = position;
        }

        public PositionMessage(Vector2 position, long networkId)
        {
            Position = position;
            NetworkId = networkId;
        }

        public void SendToServer(NetClient client)
        {
            var msg = client.CreateMessage();
            msg.Write(Action);
            msg.Write(Position.X);
            msg.Write(Position.Y);
            client.SendMessage(msg, NetDeliveryMethod.ReliableSequenced);
        }

        public void SendToClient(NetServer server, NetConnection recipient)
        {
            var msg = server.CreateMessage();
            msg.Write(Action);
            msg.Write(NetworkId);
            msg.Write(Position.X);
            msg.Write(Position.Y);
            server.SendMessage(msg, recipient, NetDeliveryMethod.ReliableSequenced);
        }

        public static PositionMessage ReceiveFromServer(NetIncomingMessage msg)
        {
            var networkId = msg.ReadInt64();
            var x = msg.ReadFloat();
            var y = msg.ReadFloat();

            var message = new PositionMessage(new Vector2(x, y));
            message.NetworkId = networkId;
            return message;
        }

        public static PositionMessage ReceiveFromClient(NetIncomingMessage msg)
        {
            var networkId = msg.SenderConnection.RemoteUniqueIdentifier;
            var x = msg.ReadFloat();
            var y = msg.ReadFloat();

            var message = new PositionMessage(new Vector2(x, y));
            message.NetworkId = networkId;
            return message;
        }
    }
}
